package ac.github.os.api

import ac.github.os.OriginSkill
import ac.github.os.api.central.SkillCentral
import ac.github.os.api.event.skill.OriginSkillCastEvent
import ac.github.os.api.pair.DataPair
import ac.github.os.internal.core.config.StringConfig
import ac.github.os.internal.core.holder.Holder
import ac.github.os.internal.core.skill.Skill
import ac.github.os.internal.core.skill.SkillScheme
import ac.github.os.internal.core.trigger.IdTrigger
import ac.github.os.internal.core.trigger.Trigger
import ac.github.os.internal.session.Session
import ink.ptms.adyeshach.taboolib.common5.Coerce
import org.bukkit.entity.Player
import taboolib.common.platform.function.info

object OriginSkillAPI {

    fun cast(trigger: Trigger, holder: Holder) {
        OriginSkill.schemes
            .filter { it.holders.contains(holder.namespace) }
            .forEach { cast(trigger, it, holder) }
    }

    fun cast(trigger: Trigger, skillName: String, holder: Holder): Boolean {
        val skillScheme = OriginSkill.schemes.firstOrNull { it.key == skillName }?.apply {
            cast(trigger, this, holder)
        }
        return skillScheme != null
    }

    fun screen(session: Session, conditions: List<String>): Boolean {
        return conditions.isEmpty() || conditions.all {
            val dataPair = check(it)
            val firstOrNull = OriginSkill.conditions.firstOrNull { it.namespace == dataPair.key }
            if (firstOrNull == null) {
                info("无效的条件 ${dataPair.key}")
                false
            } else {
                dataPair.value.initial(session)
                firstOrNull.doScreen(session, dataPair.value)
            }
        }
    }


    fun cast(trigger: Trigger, skillScheme: SkillScheme, holder: Holder) {
        val session = Session(trigger, holder)
        val all = screen(session, skillScheme.conditions)

        if (all) {
            // 释放技能

            if (trigger is IdTrigger) {
                if (SkillCentral.end(trigger, skillScheme)) {
                    SkillCentral.included(
                        trigger, skillScheme,
                        System.currentTimeMillis() + skillScheme.cooldown * 1000L
                    )
                    cast(trigger, skillScheme, session)
                }
            } else {
                cast(trigger, skillScheme, session)
            }

        }

    }

    fun cast(trigger: Trigger, skillScheme: SkillScheme, session: Session) {
        val skills = skillScheme.skills
        OriginSkillCastEvent(trigger, session).call()
        skills.forEach { Skill(it).cast(session) }
    }

    fun check(string: String): DataPair<String, StringConfig> {
        val indexOf = string.indexOf('{')
        return if (indexOf != -1) {
            DataPair(string.substring(0, indexOf), StringConfig(string.substring(indexOf)))
        } else {
            DataPair(string, StringConfig())
        }
    }


}